# -*- coding: UTF-8 -*-
# @Time    : 2021/8/28 12:09
# @Author  : Sun
# @Email   : xxxxxxxxxxx@xxx.com
# @File    : write_log.py
# @software: PyCharm
# 文件注释  :
# -*- coding: UTF-8 -*-
import logging
import time

"""默认打印warning以上级别的日志"""
class WriteLog:

    def __init__(self):
        # os.mkdir(f"./log/log_{time.strftime('%Y-%m-%d',time.localtime(time.time()))}.txt")
        # 创建日志器对象
        self.log = logging.getLogger()
        """
        每次被调用后，清空已经存在handler
        不清空会导致Handler一直递增，每调用一次都会+1，log打印也会每次调用多加一条
        """
        self.log.handlers.clear()
        # 日志总级别
        self.log.setLevel(level="DEBUG")

    def console_handler(self):
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        # 定义控制台日志级别
        console_handler.setLevel(level="INFO")
        # console_handler.setLevel(level="WARNING")
        # 设置日志输出格式
        console_handler.setFormatter(self.get_fmt()[0])
        return console_handler

    def file_handler(self):
        # 创建文件处理器
        # 不带文件名
        # file_handler = logging.FileHandler(f"./log.txt", mode='a', encoding="utf-8")
        # 这里的./对应的根目录是项目根目录JJProps
        filename = f"./log/log_{time.strftime('%Y-%m-%d',time.localtime(time.time()))}.txt"
        file_handler = logging.FileHandler(filename=filename, mode='a', encoding="utf-8")
        # 定义文件日志级别
        file_handler.setLevel(level="INFO")
        # file_handler.setLevel(level="WARNING")
        # 设置日志输出格式
        file_handler.setFormatter(self.get_fmt()[1])
        return file_handler

    def get_fmt(self):
        # 定义日志的输出格式
        console_fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)")
        file_fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)")
        return console_fmt, file_fmt

    def write_log(self):
        self.log.addHandler(self.console_handler())
        self.log.addHandler(self.file_handler())
        # 返回日志实力对象
        return self.log


if __name__ == '__main__':
    w = WriteLog()
    logger = w.write_log()
    logger.info("1111111111")
